package com.gimi.cloud.bbp.merchantZone.common.springUtil;

import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.bbp.common.constant.RedisKeyConstant;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.bbp.commonService.redis.RedisService;
import com.gimi.cloud.bbp.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.bbp.entity.sys.SysConfigEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.List;


/**
 * 初始化配置
 * Created by shazhiwei on 2017/9/6.
 *
 */
@Component
public class InitConfig implements CommandLineRunner {
	private static Logger logger = LoggerFactory.getLogger(InitConfig.class);
	private SysConfigDao sysConfigDao;
	private RedisService redisService;
	@Autowired
	public InitConfig(SysConfigDao sysConfigDao, RedisService redisService) {
		this.sysConfigDao = sysConfigDao;
		this.redisService = redisService;
	}

	@Override
	public void run(String... arg0) throws Exception {
		Example example = new Example(SysConfigEntity.class);
		example.createCriteria().andEqualTo("isDelete",0)
				.andEqualTo("cfIsGlobal",1);
		List<SysConfigEntity> configList = sysConfigDao.selectByExample(example);
		if(configList != null && configList.size() > 0){
			for (SysConfigEntity tempConfig : configList) {
				if(!StringUtil.isBlank(tempConfig.getCfKey())){
					redisService.set(RedisKeyConstant.BBP_CONFIG_PREFIX +tempConfig.getCfKey(),tempConfig.getCfValue());
				}else{
					logger.error("初始化"+tempConfig.getCfKey()+"配置异常，值为空，请确认配置表数据");
				}
			}
		}
		initAliOssInfo();
	}

	private void initAliOssInfo(){
		logger.info("开始初始化AliOss帐号信息");
		JSONObject aliOssAccount = redisService.getJSONObjectConfigByKey(RedisKeyConstant.CONFIG_ALIOSS_ACCOUNT);
		if(null == aliOssAccount){
			logger.info("初始化AliOss帐号信息失败");
		}
		AliOSSUtil.init(aliOssAccount.getString("endpoint"),aliOssAccount.getString("accessKeyId"),
				aliOssAccount.getString("accessSecret"),aliOssAccount.getString("bucketName"));
	}

}
